package com.forlove.app.qselect.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.forlove.app.ForloveApplication;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.PinEntryEditText;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.UpLoadContactsAsync;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.GpsEntity;
import com.forlove.app.qselect.login.entity.LoginEntity;
import com.forlove.app.qselect.login.entity.RegisterEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.presenter.RegisterPhonePresenter;
import com.forlove.app.qselect.login.view.IRegisterPhoneView;
import com.forlove.app.qselect.login.widget.ErrorMessageView;
import com.forlove.app.qselect.login.widget.RegisterPhoneView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 填写手机号页面
 * Created by yjl on 2017/10/9.
 */

public class RegisterPhoneActivity extends BaseActivity implements
        View.OnClickListener, IRegisterPhoneView,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>> {
    public static final String COME_FROM = "come_from";
    public static final String FROM_REGISTER = "from_register";//注册跳转
    public static final String FROM_LOGIN = "from_login";//跳转登录
    @BindView(R.id.edittext_input_phone)
    AppCompatEditText edittext_input_phone;

    @BindView(R.id.view_input_phone)
    LinearLayout view_input_phone;  //输入手机号页面

    @BindView(R.id.view_input_code)
    LinearLayout view_input_code; //验证验证码页面

    @BindView(R.id.view_input_pw)
    LinearLayout view_input_pw;  //设置密码页面

    @BindView(R.id.bt_register_nextstep)
    TextView bt_register_nextstep; //输入号码下一步

    @BindView(R.id.bt_identify_nextstep)
    TextView bt_identify_nextstep; //输入验证码下一步

    @BindView(R.id.bt_register_finish)
    TextView bt_register_finish; //完成注册

    @BindView(R.id.text_back)
    TextView text_back;

    @BindView(R.id.edittext_input_code)
    PinEntryEditText pinEntryEditText;

    @BindView(R.id.text_hint)
    TextView hintTextView;

    @BindView(R.id.view_error_message)
    ErrorMessageView view_error_message;//错误信息提示

    @BindView(R.id.view_register)
    RegisterPhoneView view_register;

    @BindView(R.id.text_send_phone_again)
    TextView text_send_phone_again;// 重新发送验证码

    @BindView(R.id.edittext_input_pw)
    AppCompatEditText edittext_input_pw;//输入密码

    @BindView(R.id.edittext_input_pw_again)
    AppCompatEditText edittext_input_pw_again; //再次输入验证码

    private RegisterPhonePresenter registerPhonePresenter;
    private String phoneCode;//手机号
    private String identifyCode;//验证码
    private LoginEntity loginEntity = new LoginEntity();
    private int second = 60;
    private String mPW;
    private String mPWAgain;
    private UpLoadContactsAsync upLoadContactsAsync;
    //    private CountDownTimer timer;
    private Handler handler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_register_phone;
    }


    @Override
    public void initView() {
        registerPhonePresenter = new RegisterPhonePresenter(this);
        setPresenter(registerPhonePresenter);
        handler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 99999) {
                    second--;
                    text_send_phone_again.setText(second + "秒后重发");
                    text_send_phone_again.setOnClickListener(null);
                    if (second <= 0) {
                        second = 60;
                        text_send_phone_again.setText("重新发送");
                        text_send_phone_again.setOnClickListener(RegisterPhoneActivity.this);
                    } else {
                        handler.sendEmptyMessageDelayed(99999, 1000);
                    }

                }
            }
        };
        text_send_phone_again.setOnClickListener(this);
        bt_register_nextstep.setOnClickListener(this);
        bt_identify_nextstep.setOnClickListener(this);
        text_back.setOnClickListener(this);
        bt_register_finish.setOnClickListener(this);
        pinEntryEditText.setHintTextView(hintTextView);
        initEditeStatus();
//        showSendAgainPhone();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    private void showSendAgainPhone() {
        text_send_phone_again.setVisibility(View.VISIBLE);
        text_send_phone_again.setText(second + "秒后重发");
        handler.sendEmptyMessageDelayed(99999, 1000);
//        /** 倒计时,一次1秒 */
//        timer = new CountDownTimer(60 * 1000, 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                second = (int) (millisUntilFinished / 1000);
//                text_send_phone_again.setText(second + "秒后重发");
//            }
//
//            @Override
//            public void onFinish() {
//                second = 60;
//                text_send_phone_again.setText("重新发送");
//            }
//        };
//        timer.start();

    }

    /**
     * 输入手机号
     */
    private void requestPhoneCorrect() {
        phoneCode = edittext_input_phone.getText().toString();
        if (!StringUtils.isMobile(phoneCode)) {
            view_error_message.setError("请输入正确的手机号码！");
            view_error_message.setVisibility(View.VISIBLE);
            return;
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(phoneCode);
//        String aesPw = CipherUtils.md5();
        String time = MyTimeUtils.formatDate(new Date(System.currentTimeMillis()), "yyyyMMdd");
        stringBuilder.append(time);
//        LogUtil.e("yjl", "明文:" + stringBuilder.toString());
        String md5code = CipherUtils.md5(stringBuilder.toString());
        String sign = CryptAES.AES_Encrypt(md5code, phoneCode);
//        LogUtil.e("yjl", "密文：" + sign);
        registerPhonePresenter.loadPhoneData(phoneCode, sign);
    }

    private void requestIdentifyCode() {
        identifyCode = pinEntryEditText.getText().toString();
        LogUtil.e("yjl", "code:" + identifyCode);
        if (TextUtils.isEmpty(identifyCode)
                || identifyCode.length() < 6) {
            view_error_message.setVisibility(View.VISIBLE);
            view_error_message.setError("请输入验证码!");
            return;
        }
        Map<String, String> param = new HashMap<>();
        param.put("mobile", phoneCode);
        param.put("msgCode", identifyCode);
        registerPhonePresenter.loadIdentifyCode(param);
    }

    private void requestSetPW() {
        if (!StringUtils.isNotEmpty(mPW) && !StringUtils.isNotEmpty(mPWAgain)) {
            view_error_message.setVisibility(View.VISIBLE);
            view_error_message.setError("请输入密码！");
            return;
        }
        if (!mPW.equals(mPWAgain)) {
            view_error_message.setVisibility(View.VISIBLE);
            view_error_message.setError("两次密码不一致！");
            return;
        }
        if (!TextUtils.isEmpty(mPW) && (mPW.length() < 6 || mPW.length() > 32)) {
            view_error_message.setVisibility(View.VISIBLE);
            view_error_message.setError("请输入6-32位密码！");
            return;
        }
        loginEntity.mobile = phoneCode;
        loginEntity.password = CipherUtils.md5(mPW);
//        String logcation = LocationUtils.getBestLocationString(this);

        GpsEntity gpsEntity = DataManager.getLocation(this);
        if (gpsEntity != null) {
            loginEntity.location = gpsEntity.lat + "," + gpsEntity.lng;
            LogUtil.e("yjl", "经纬度：" + loginEntity.location);
        }
        registerPhonePresenter.loadSetPWData(loginEntity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_register_nextstep:
                requestPhoneCorrect();
                break;
            case R.id.bt_identify_nextstep:
                requestIdentifyCode();
                break;
            case R.id.text_back:
                view_register.showInputPhoneView();
                break;
            case R.id.bt_register_finish:
                requestSetPW();
                break;
            case R.id.text_send_phone_again:
                if (second == 0 || second == 60) {
                    showSendAgainPhone();
                    //TODO 重新发送
                    requestPhoneCorrect();
                }
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (view_register != null) {
            if (view_register.getCurrentPosition() == RegisterPhoneView.POSITION_INPUT_PHONE) {
                super.onBackPressed();
            } else if (view_register.getCurrentPosition() == RegisterPhoneView.POSITION_CODE_IDENTIFY) {
                view_register.showInputPhoneView();
            } else if (view_register.getCurrentPosition() == RegisterPhoneView.POSITION_SET_PW) {
                view_register.showCodeIdentifyView();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    private void initEditeStatus() {
        pinEntryEditText.setOnPinEnteredListener(new PinEntryEditText.OnPinEnteredListener() {
            @Override
            public void onPinEntered(CharSequence str) {
                if (!TextUtils.isEmpty(str)) {
                    bt_identify_nextstep.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_identify_nextstep.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }
            }
        });
        edittext_input_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    bt_register_nextstep.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_register_nextstep.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }
            }
        });
        edittext_input_pw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPW = s.toString();
                if (!TextUtils.isEmpty(mPW) && !TextUtils.isEmpty(mPWAgain)) {
                    bt_register_finish.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_register_finish.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }
            }
        });
        edittext_input_pw_again.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPWAgain = s.toString();
                if (!TextUtils.isEmpty(mPW) && !TextUtils.isEmpty(mPWAgain)) {
                    bt_register_finish.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_register_finish.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }

            }
        });
    }

    @Override
    public void showRequestPhoneView(final RegisterEntity registerEntity, final String error) {
        if (registerEntity != null) {
            if (!TextUtils.isEmpty(registerEntity.msg)) {
                view_error_message.setError(registerEntity.msg);
                view_error_message.setVisibility(View.VISIBLE);
                view_register.showCodeIdentifyView();
                second = 60;
                handler.sendEmptyMessageDelayed(99999, 1000);
            } else {
                UserEntity userEntity = new UserEntity();
                userEntity.userMobile = phoneCode;
                userEntity.mUserImage = registerEntity.img;
                userEntity.userName = registerEntity.username;
                Intent intent = new Intent();
                intent.setClass(RegisterPhoneActivity.this, LoginInputPWActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("userinfo", userEntity);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        } else {
            view_error_message.setError(error);
            view_error_message.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showIdentifyCodeView(final int resultCode, final LoginEntity entity) {
        view_error_message.setError(entity.message);
        view_error_message.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(entity.valid_token)
                && resultCode == NetworkManager.ResultCode.RESULT_SUCCESS.getValue()) {
            view_register.showSetPwView();
            loginEntity = entity;
        }
    }

    @Override
    public void showSetPassWordView(final int resultCode, final UserEntity userEntity, final String FailMsg) {

        if (resultCode == NetworkManager.ResultCode.RESULT_SUCCESS.getValue()) {
            getSupportLoaderManager().restartLoader(UpLoadContactsAsync.ASYNC_ID, null, RegisterPhoneActivity.this);
            view_error_message.setError("注册成功！");
            userEntity.regId = UserManager.getJPushID(this);
            UserManager.saveLoginState(this, true);
            UserManager.saveUserInfo(this, userEntity);
            //TODO 跳转信息设置
            if (!TextUtils.isEmpty(userEntity.regId)) {
                registerPhonePresenter.loadUpJPushRegisterId();
            }
            startActivity(new Intent(this, SetUserInfoActivity.class));
            finish();
        } else {
            view_error_message.setError(FailMsg);
        }
        view_error_message.setVisibility(View.VISIBLE);

    }

    private UpLoadContactsAsync createContacts() {
        if (upLoadContactsAsync == null) {
            upLoadContactsAsync = new UpLoadContactsAsync(this);
        }
        return upLoadContactsAsync;
    }

    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        ContactsManager.saveContactsFriend(ForloveApplication.getInstance(), data);
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

    }
}
